package com.hula.onion.book.server.spider.platforms.edspay;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hula.onion.book.server.common.CommonResponse;
import com.hula.onion.book.server.common.LoginForm;
import com.hula.onion.book.server.config.ResponseStatusEnum;
import com.hula.onion.book.server.model.AccountInfo;
import com.hula.onion.book.server.utils.CookieUtils;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by work on 2018/3/16.
 */
@Component
public class EDSPaySpiderHelper {
    /**
     * 组装请求参数
     *
     * @param form
     * @return
     */
    public Map<String, Object> installRequestParams(LoginForm form) {

        Map<String, Object> map = new HashMap<>(4);
        List<BasicClientCookie> cookies = CookieUtils.getCookieCache(form.getPlatformId(),
                form.getUserId());
        for (BasicClientCookie cookie : cookies) {
            if ("captchaId".equals(cookie.getName())) {
                map.put("captchaId", cookie.getValue());
            }
        }
        map.put("userName", form.getUserName());
        map.put("pwd", form.getPassword());
        map.put("validCode", form.getTicket());
        return map;

    }

    public Map<String, Object> installLoginRequestParams(String token) {
        Map<String, Object> map = new HashMap<>(4);
        map.put("token", token);
        return map;
    }

    /**
     * 解析账户余额
     *
     * @param json
     * @return
     */
    public CommonResponse parseAccountBalance(String json) {
        try {
            JSONObject jsonObject = JSON.parseObject(json);
            if (jsonObject.getBoolean("success")) {
                AccountInfo accountInfo = new AccountInfo();
                JSONObject accountJson = jsonObject.getJSONObject("resData").getJSONObject("basicModel");
                accountInfo.setAmount(accountJson.getBigDecimal("totalMoney"));
                accountInfo.setWaitIntrest(accountJson.getBigDecimal("waitInterest"));
                accountInfo.setYesterdayIntrest(accountJson.getBigDecimal("yesterdayEarnAmount"));
                accountInfo.setTotalIntrest(accountJson.getBigDecimal("earnAmount"));
                return new CommonResponse(accountInfo);
            }
            return new CommonResponse(ResponseStatusEnum.QUERY_FAIL);
        } catch (Exception e) {
            return new CommonResponse(ResponseStatusEnum.QUERY_FAIL);
        }
    }
}
